﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
using DDE_Server.Event;
using DDE_Server.Object;
using DDE_Server.View;

namespace DDE_Server.Presenter
{
    public class DispatchPresenter
    {
        private event DispRateChangedEventHandler dispRateChanged;
        private DDEConfigs config = null;
        private DispatchView view = null;
        Timer timer = null;
        

        public DispatchPresenter(DispatchView view, DDEConfigs config) 
        {
            this.view = view;
            this.config = config;
            //RefreshData();
            timer = new Timer(config.timer * 100);
            timer.Elapsed += new ElapsedEventHandler(RefreshDataElapsed);
            timer.Enabled = true;
        }

        public event DispRateChangedEventHandler DispRateChanged 
        {
            add {
                if (dispRateChanged == null || !dispRateChanged.GetInvocationList().Contains(value)) {
                    dispRateChanged += value;
                }
            }
            remove {
                dispRateChanged -= value;
            }
        }

        private void RaiseDispRateChanged(PjmInstDispRate info)
        {
            DispRateChangedEventHandler handler = dispRateChanged;
            if (handler != null)
            {
                handler(this, new DispRateChangedEventArgs(info));
            }
        }

        public void RefreshData() {
            PasserWebPage webLoad = new PasserWebPage();
            if (webLoad.Passer(config.url))
            {
                view.InstDispRate = webLoad.DispRate;
                RaiseDispRateChanged(webLoad.DispRate);
            }
        }

        public void RefreshDataElapsed(object sender, ElapsedEventArgs e)
        {
            RefreshData();
        }

    }
}
